/* 
    发布帖子数据模型
*/
import { SchemaFactory, Schema, Prop } from '@nestjs/mongoose'
import mongoose, { Document } from 'mongoose'
import { Collect } from './collect.schema'
export type PropositionDocument = Proposition & Document

@Schema({ timestamps: true })
export class Proposition {
  //帖子标题
  @Prop({ required: true })
  title: string
  //帖子描述
  @Prop()
  description: string | null
  //发布者
  @Prop({ required: true, ref: 'User' })
  user: mongoose.Types.ObjectId
  //所属贴吧
  @Prop({ required: true, ref: 'Bar' })
  bar: mongoose.Types.ObjectId
  //评论数
  @Prop({ default: 0 })
  commentCount: number
  //被收藏数量
  @Prop({ default: 0 })
  beCollectCount: number
  //帖子点赞数
  @Prop({ default: 0 })
  likeCount: number

  //帖子主题图片 保存图片名文件路径
  @Prop({ default: [] })
  imageList: Array<{ url: string; filename: string }>
}

const PropositionSchema = SchemaFactory.createForClass(Proposition)

PropositionSchema.pre('remove', async function () {
  //删除关联的收藏集合
  const result = await this.$model(Collect.name).find({ proposition: this._id.toString() })

  await result.forEach(async (doc) => {
    await doc.remove()
  })
  //删除关联的评论集合
  const comment = await this.$model('Comment').find({ proposition: this._id.toString() })
  await comment.forEach(async (doc) => {
    await doc.remove()
  })
  //删除关联的点赞集合
  const like = await this.$model('Like').find({ proposition: this._id.toString() })
  await like.forEach(async (doc) => {
    await doc.remove()
  })
})

export { PropositionSchema }
